package colopl.http.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import colopl.http.client.ColoplHttpRequestFactory;
import colopl.http.client.ColoplHttpRequestUtil;
import colopl.http.client.ColoplUser;
import colopl.http.util.MessageResource;
import colopl.http.util.RegexUtil;

import gae.util.http.client.HttpRequest;
import gae.util.http.client.HttpResponse;

/**
 * コロプラにログインするためのクラス
 * @author osora
 */
public class ColoplLoginService {

    public ColoplHttpRequestFactory factory = new ColoplHttpRequestFactory();

    public String hdbRegexp = "<input value=\"(.+)\" name=\"hdb\" type=\"hidden\"/>";

    public String valueRegexp = "<input value=\"(.+)\" name=\"submit\" src=\"";
    
    public String idRegexp = "http://colopl\\.jp/s/main\\.do\\?id=(.+)&amp;uid=";
    
    public String uidRegexp = "http://colopl\\.jp/s/main\\.do\\?id=[0-9]+&amp;uid=(.+)&amp;guid=ON\">";
    
    
    
    /**
     * ログインする
     * 
     * @param username
     * @param password
     * @return ユーザ情報
     * @throws ColoplLoginException
     */
    public ColoplUser login(String username, String password)
            throws ColoplLoginException {
        
        ColoplUser user = new ColoplUser();
        user.setUsername(username);
        user.setPassword(password);
        
        // access PC Top page
        HttpRequest req = factory.createPcTop();
        HttpResponse res = null;
        try {
            res = req.execute();
        } catch (IOException e1) {
            throw new ColoplLoginException(MessageResource.getMessage("CHC-101", req), e1);
        }
        ColoplHttpRequestUtil.updateCookie(user, res);
        
        List<String> hdbs = new ArrayList<String>();
        List<String> values = new ArrayList<String>();
        RegexUtil regex1 = new RegexUtil();
        regex1.addRegex(hdbRegexp, hdbs);
        regex1.addRegex(valueRegexp, values);
        try {
            regex1.parse(res.getConnection().getInputStream());
        } catch (IOException e1) {
            throw new ColoplLoginException(MessageResource.getMessage("CHC-102", res), e1);
        } finally {
            res.getConnection().disconnect();
        }

        // get "hdb" and "submit" value.
        if (hdbs.size() < 1 || values.size() < 1) {
            throw new ColoplLoginException(MessageResource.getMessage("CHC-103", hdbs, values, res));
        }
        String hdb = hdbs.get(0);
        String value = values.get(0);

        // login
        HttpRequest req2 = factory.createPcTopLogin(user, value, hdb);
        HttpResponse res2 = null;
        try {
            res2 = req2.execute();
            ColoplHttpRequestUtil.updateCookie(user, res2);
        } catch (IOException e) {
            throw new ColoplLoginException(MessageResource.getMessage("CHC-104", req2), e);
        } finally {
            if (res2 != null) {
                res2.getConnection().disconnect();
            }
        }
        
        // authenticate
        String location = null;
        HttpRequest req3 = factory.createAuthenticationEntrance(user);
        HttpResponse res3 = null;
        try {
            res3 = req3.execute();
            ColoplHttpRequestUtil.updateCookie(user, res3);
            location = res3.getHeader().get("Location").get(0);
        } catch (IOException e) {
            throw new ColoplLoginException(MessageResource.getMessage("CHC-105", req3), e);
        } finally {
            if (res3 != null) {
                res3.getConnection().disconnect();
            }
        }
        
        // access Colopl Top page
        HttpRequest req4 = factory.createLocation(user, location);
        HttpResponse res4 = null;
        try {
            res4 = req4.execute();
            ColoplHttpRequestUtil.updateCookie(user, res3);
        } catch (IOException e) {
            throw new ColoplLoginException(MessageResource.getMessage("CHC-106", req4), e);
        }
        
        List<String> ids = new ArrayList<String>();
        List<String> uids = new ArrayList<String>();
        RegexUtil regex2 = new RegexUtil();
        regex2.addRegex(idRegexp, ids);
        regex2.addRegex(uidRegexp, uids);
        try {
            regex2.parse(res4.getConnection().getInputStream());
        } catch (IOException e1) {
            throw new ColoplLoginException(MessageResource.getMessage("CHC-107", ids, uids, res4), e1);
        } finally {
            if (res4 != null) {
                res4.getConnection().disconnect();
            }
        }
        
        // get "id" and "uid" value.
        if (ids.size() < 1 || uids.size() < 1) {
            throw new ColoplLoginException(MessageResource.getMessage("CHC-107", ids, uids, res4));
        }
        user.setId(ids.get(0));
        user.setUid(uids.get(0));
        
        return user;
    }
    
}
